package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.vo.DishVO;
import com.itheima.reggie.common.R;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    //--1-- 分页查询   /dish/page?page=1&pageSize=10&name=xxx
    @GetMapping("/page")
    public R selectByPage(Long page,Long pageSize,String name){

        //--1------分页、条件构造器，查到分页数据
        Page<Dish> pageDish=new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> qwr=new LambdaQueryWrapper<>();
        qwr.like(Objects.nonNull(name),Dish::getName,name)
                .orderByDesc(Dish::getUpdateTime);//新加的在前面

        dishService.page(pageDish,qwr);
        log.info("[>>>分页构造器--pageDish]:{}",pageDish);
        log.info("[>>>分页构造器--pageDish.getRecords()]:{}",pageDish.getRecords());

        //--2------从构造器取出对象集合，封装到`VO`集合_____得到VO
        List<Dish> dishList = pageDish.getRecords();
        List<DishVO> dishVOList=dishList.stream().map(dish -> {
            //遍历，拷贝对象__并加入新字段
            DishVO dishVO=new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            Category category = categoryService.getById(dish.getCategoryId());
            dishVO.setCategoryName(category.getName());
            return dishVO;
        }).collect(Collectors.toList());

        //--3------VO分页构造器，复制对象
        Page<DishVO> pageDishVO=new Page<>();
        BeanUtils.copyProperties(pageDish,pageDishVO,"records"); //设置总条数
        pageDishVO.setRecords(dishVOList);  //设置分页数据
        return R.success(pageDishVO);
    }

    //--2-- 新增
    /**
     * 新增菜品
     * @param dishVO
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishVO dishVO){
        log.info("[>>>菜品新增--dishVO]:{}",dishVO);
        dishService.saveWithFlavor(dishVO);

        //清理当前菜品的缓存数据
        redisTemplateKeyClean(dishVO.getCategoryId());
        return R.success("新增菜品成功");
    }



    //--3-- 修改---传id，回显数据
    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id){
        log.info("[>>>修改菜品--传id回显数据]:{}",id);

        //源对象拷贝
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dishService.getById(id),dishVO);

        List<DishFlavor> list = dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, id));
        dishVO.setFlavors(list);
        return R.success(dishVO);
    }

    //--3-2-- 修改---
    @PutMapping()
    public R update(@RequestBody DishVO dishVO){
        log.info("[>>>修改菜品--dishVO]:{}",dishVO);
        dishService.updateWithFlavor(dishVO);

        //清理【所有】菜品的缓存数据
        redisTemplateKeyClean();
        return R.success("修改菜品成功");
    }


    //--4-- 删除---   1删除  0不删除
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids){
        log.info("[>>>删除菜品--ids]:{}",ids);

        //内置删除会直接删表---删除dish
        dishService.removeByIds(ids);

        //删除dishids--关联的dishFlavor表
        dishFlavorService.remove(new LambdaQueryWrapper<DishFlavor>().in(DishFlavor::getDishId,ids));
        return R.success("删除成功");
    }


    //--5-- 起售/停售 批量起售/批量停售
    @PostMapping("/status/{num}")
    public R restatus(@RequestParam List<Long> ids,@PathVariable Integer num){
        log.info("[>>>起售/停售--ids]:{}",ids);
        dishService.restatusByIds(ids,num);
        return R.success("操作成功");
    }




    //--2---  【根据分类id查询该分类下的所有菜品集合】
    //___请求url地址：dish/list?categoryId=1397844263642378242&status=1
    @GetMapping("/list")
    public R<List<DishVO>> selectDish(Dish dish){

        Long categoryId=dish.getCategoryId();
        Integer status=dish.getStatus();
        log.info("[>>>分类id查询该分类下的所有菜品--传入参数]:categoryId={},status={}",categoryId,status);

        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1
        //先从redis中获取缓存数据
        List<DishVO> dishVOList= (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(dishVOList != null){
            //如果存在，直接返回，无需查询数据库
            log.info("[>>> 读取缓存 <<<]:--categoryId={}",categoryId);
            return R.success(dishVOList);
        }

        //--T1  分类id_查该分类包含的__正在售卖的dish集合
        LambdaQueryWrapper<Dish> qwr=new LambdaQueryWrapper<>();
        qwr.eq(Objects.nonNull(categoryId),Dish::getCategoryId,categoryId)
                .eq(Dish::getStatus,1).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(qwr);
        log.info("[>>>菜品id--{}]:DishList={}",categoryId,dishList);

        //--T2  集合中每个dish查到口味数据
        dishVOList=dishList.stream().map(item->{
            DishVO dishVO=new DishVO();
            //————封装[菜品]
            BeanUtils.copyProperties(item,dishVO);
            //————封装[口味列表]
            dishVO.setFlavors(
                    dishFlavorService.list(
                            new LambdaQueryWrapper<DishFlavor>()
                                    .eq(DishFlavor::getDishId,item.getId())));
            //————封装[菜品名称]
            dishVO.setCategoryName(
                    categoryService.getOne(
                            new LambdaQueryWrapper<Category>()
                                    .eq(Category::getId,categoryId)).getName()
            );
            return dishVO;
        }).collect(Collectors.toList());

        //--T3  返回结果
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishVOList,60, TimeUnit.MINUTES);
        return R.success(dishVOList);   //new List<DishVO>
    }


    //清除缓存
    public void redisTemplateKeyClean(){
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        log.info("[>>> 删除缓存 <<<]:--以dish_xxx开头的key");
    }
    public void redisTemplateKeyClean(Long categoryId){
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" +categoryId+ "_1";
        redisTemplate.delete(key);
        log.info("[>>> 删除缓存 <<<]:--删除key=dish_{}",categoryId);
    }

//    public R<List<Dish>> selectDish_1(Long categoryId){
//        return R.success(
//                dishService.list(
//                        new LambdaQueryWrapper<Dish>()
//                                .eq(Dish::getCategoryId,categoryId)
//                                .orderByDesc(Dish::getUpdateTime)));
//    }















    //--------------------------------------------------


    //--1-- 分页查询   /dish/page?page=1&pageSize=10&name=xxx
    //@GetMapping("/page")
    public R selectByPage_1(Long page,Long pageSize,String name){
        //--【分页构造器】
        Page<Dish> pageDish=new Page<>(page,pageSize);
        //--【条件构造器】
        LambdaQueryWrapper<Dish> qwr=new LambdaQueryWrapper<>();
        qwr.like(name!=null && !"".equals(name),Dish::getName,name);
        dishService.page(pageDish,qwr);

        return R.success(pageDish);
    }
    //--2--
    public R selectByPage_VO(Long page,Long pageSize,String name){
        //--【分页构造器】
        Page<Dish> pageDish=new Page<>(page,pageSize);
        //--【条件构造器】
        LambdaQueryWrapper<Dish> qwr=new LambdaQueryWrapper<>();
        qwr.like(Objects.nonNull(name),Dish::getName,name);

        dishService.page(pageDish,qwr);

        log.info("[>>>分页构造器--pageDish]:{}",pageDish);
        log.info("[>>>分页构造器--pageDish.getRecords()]:{}",pageDish.getRecords());

        //--4__分页数据`List<Dish>`  重新封装为`List<DishVO>`
        List<Dish> dishList = pageDish.getRecords();

        List<DishVO> dishVOList=new ArrayList<>();
        for (Dish dish : dishList) {
            DishVO dishVO = new DishVO();

            BeanUtils.copyProperties(dish,dishVO);   //-属性设置

            Category category = categoryService.getById(dish.getCategoryId());
            dishVO.setCategoryName(category.getName());   //---加入字段
            dishVOList.add(dishVO);
        }
        //--5__分页数据`List<Dish>`  重新封装为`List<DishVO>`
        Page<DishVO> pageDishVO=new Page<>();
        BeanUtils.copyProperties(pageDish,pageDishVO,"records"); //设置总条数
        pageDishVO.setRecords(dishVOList);  //设置分页数据
        return R.success(pageDishVO);
    }


}
